package com.buaa.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Title: Jackson格式转换工具类
 * Description: 
 * 		参考：http://blog.csdn.net/jackpk/article/details/43198491 
 * Company: BUAA
 *
 * @author 伟宏 
 * @date 2017年1月15日
 */
public final class JacksonUtil {

	private static ObjectMapper objectMapper;

	private static ObjectMapper getObjectMapper() {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		return objectMapper;
	}

	/** 
	 * 使用泛型方法，把json字符串转换为相应的JavaBean/集合。
	 *  
	 * (1)转换为普通JavaBean：readValue(json,Student.class) 
	 * (2)转换为List,如List<Student>,将第二个参数传递为Student 
	 * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List 
	 *  
	 * @param jsonStr : String json字符串
	 * @param valueType 
	 * @return 
	 */
	public static <T> T readValue(String jsonStr, Class<T> valueType) {
		objectMapper = getObjectMapper();
		try {
			return objectMapper.readValue(jsonStr, valueType);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 
	 * json数组转List 
	 * @param jsonStr 
	 * @param valueTypeRef 
	 * @return 
	 */
	public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
		objectMapper = getObjectMapper();
		try {
			return objectMapper.readValue(jsonStr, valueTypeRef);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 
	 * 把JavaBean/集合类型转换为json字符串 
	 *  
	 * @param object : Object JavaBean/集合 
	 * @return 
	 * 		String : json字符串
	 */
	public static String toJSon(Object object) {
		objectMapper = getObjectMapper();
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}